import axios from 'axios'
import store from '../store'
import { message } from 'ant-design-vue/lib'
import { apiHost } from '@/config/env'
// import router from '../router'

const isProd = process.env.NODE_ENV === 'production'

// 引入环境host
axios.defaults.baseURL = isProd ? apiHost : '/api'
// axios.defaults.baseURL = apiHost

// request拦截器
axios.interceptors.request.use(config => {
  if (store.state.token) {
    config.headers.Authorization = `Bearer ${store.state.token}`
  }
  return config
})

// response拦截器
axios.interceptors.response.use(response => {
  switch (response.data.code) {
    // 成功
    case 100000:
      return response.data
      // token失效
    case 120004:
      store.dispatch('logout')
      message.warn({
        content: '跳转登录'
      })
      return Promise.reject(response.data)
      // 其他
    default:
      message.error({
        content: response.data.message
      })
      return Promise.reject(response.data)
  }
}, err => {
  console.log(err.response)
  if (err.response && err.response.status) {
    switch (err.response.status) {
      case 401:
        store.dispatch('logout')
        message.warn({
          content: '跳转登录'
        })
        return Promise.reject(err)
      default:
        message.error({
          content: '服务器错误'
        })
        break
    }
  }
  return Promise.reject(err)
})

export default axios
